﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlackBird.Models;

namespace BlackBird.DataAccess
{
    public static class ShenheDataAccess
    {
        public static void SaveBijiadanSheheToDatabase(string bijiadanId, CommentDM comment)
        {
            SaveBijiadanSheheToDatabase(Convert.ToInt32(bijiadanId), comment);
        }

        public static void SaveBijiadanSheheToDatabase(int bijiadanId, CommentDM comment)
        {
            using (var dbContext = new blackbirdEntities())
            {
                var shenheId = SaveSheheToDatabase(comment.Content, comment.UserName, comment.Operation);

                var bijiadanshenheObj = new bijiadan_shenhe()
                {
                    Shenhe_idShenhe = shenheId,
                    Bijiandan_idBijiandan = bijiadanId 
                };

                dbContext.bijiadan_shenhe.AddObject(bijiadanshenheObj);
                dbContext.SaveChanges();
            }
        }

        private static int SaveSheheToDatabase(string content, string userName, ShenHeResult shenheResult)
        {
            using (var dbContext = new blackbirdEntities())
            {
                var shenheObj = new shenhe()
                {
                    Comment = content,
                    Date = DateTime.Now,
                };

                shenheObj.User_idUser = AccountDataAccess.GetUserInfoByUserName(userName).idUser;
                shenheObj.Operation_idOperation = GlobalObjectBuffer.allOperations.Find(p =>
                    p.Name == shenheResult.ToString()).idOperation;

                dbContext.shenhe.AddObject(shenheObj);

                dbContext.SaveChanges();

                return shenheObj.idShenhe;
            }
        }

        public static List<CommentDM> GetBijiadanShenhe(string bijiadanId)
        {
            return GetBijiadanShenhe(Convert.ToInt32(bijiadanId));
        }

        public static List<CommentDM> GetBijiadanShenhe(int bijiadanId)
        {
            using (var dbContext = new blackbirdEntities())
            {
                var all_bijiadan_shenhe = dbContext.bijiadan_shenhe.Where(p => p.Bijiandan_idBijiandan == bijiadanId);
                var all_shenhe = all_bijiadan_shenhe.ToList().Select<bijiadan_shenhe, CommentDM>(p => CreateComment(p.shenhe));
                return all_shenhe.ToList();
            }
        }

        private static CommentDM CreateComment(shenhe shenheDb)
        {
            return new CommentDM()
            {
                ID = shenheDb.idShenhe.ToString(),
                Content = shenheDb.Comment,
                UserName = shenheDb.user.Name,
                Operation = (ShenHeResult)Enum.Parse(typeof(ShenHeResult), shenheDb.operation.Name),
                Date = (DateTime)shenheDb.Date
            };
        }

    }
}